package jun.comm.netkit;


import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class JunClient {

	// 连接的服务器IP地址
	private String m_ip = "";

	// 连接服务器的端口
	private int m_port = 0;

	// 信道选择器
	private Selector m_selector;

	// 与服务器通信的信道
	private SocketChannel m_sktChan;

	public void init(String ip, int port) throws Exception{
		this.m_ip = ip;
		this.m_port = port;
		
		// 打开监听信道
		m_sktChan = SocketChannel.open();
		// 连接对应的服务器
		m_sktChan.connect(new InetSocketAddress(m_ip, m_port));
		// 设置为非阻塞模式
		m_sktChan.configureBlocking(false);
		// 创建选择器
		m_selector = Selector.open();
	}

	/**
	 * 发送数据
	 * 
	 * @return
	 */
	public int send(JunProtocol junProtocol) {
		
		if(junProtocol==null || junProtocol.cont.isEmpty()){
			return -1;
		}
		
		try {
			// 注册选择器到信道
			m_sktChan.register(m_selector, SelectionKey.OP_WRITE);
			
			// 传输数据
			if (m_selector.isOpen() && m_selector.select() > 0) {

				// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
				Iterator<SelectionKey> keyIter = m_selector.selectedKeys().iterator();
				while (keyIter.hasNext()) {
					SelectionKey key = keyIter.next();
					// 移除已经拿出的键
					keyIter.remove();
					try {
						if (key.isValid() && key.isWritable()) {
							// 客户端可写时
							junProtocol.write(key);
						}
					} catch (Exception e) {
						return -2;
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e);
			return -111;
		}
		
		return 0;
	}

	/**
	 * 接收数据
	 * 
	 * @return
	 */
	public int recv(JunProtocol junProtocol) {
		
		if(junProtocol==null){
			return -1;
		}
		
		try {
			m_selector = Selector.open();
			// 注册选择器到信道
			m_sktChan.register(m_selector, SelectionKey.OP_READ);
			
			// 传输数据
			if (m_selector.isOpen() && m_selector.select() > 0) {

				// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
				Iterator<SelectionKey> keyIter = m_selector.selectedKeys().iterator();
				while (keyIter.hasNext()) {
					SelectionKey key = keyIter.next();
					// 移除已经拿出的键
					keyIter.remove();
					try {
						if (key.isReadable()) {
							// 客户端可读时
							junProtocol.read(key);
						}
					} catch (Exception e) {
						return -2;
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e);
			return -111;
		}
		return 0;
	}

}
